package com.cooperate.fly.controller;

import com.cooperate.fly.bo.Question;
import com.cooperate.fly.bo.QuestionWithBLOBs;
import com.cooperate.fly.bo.User;
import com.cooperate.fly.mapper.QuestionMapper;
import com.cooperate.fly.service.system.QuestionService;
import com.cooperate.fly.util.PropertyConstant;
import com.cooperate.fly.web.WebFrontHelper;
import com.google.gson.Gson;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/22.
 */

@Controller
@RequestMapping("/question")
@SessionAttributes(PropertyConstant.USER_SESSION_KEY)
public class QuestionController {
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private WebFrontHelper webFrontHelper;

    @RequestMapping("/list")
    @ResponseBody
    public String list(){
        return new Gson().toJson(webFrontHelper.buildQuestionGrid(this.questionService.findAll()));
    }

    @RequestMapping("/page")
    @ResponseBody
    public Map<String, Object> page(@RequestParam(value="page",defaultValue="1")int pageNo,
                                    @RequestParam(value="rows",defaultValue="20")int pageSize,
                                    @ModelAttribute(PropertyConstant.USER_SESSION_KEY)User user){
        pageNo=pageNo>0?pageNo-1:pageNo;
        Pageable pageRequest=(Pageable) new PageRequest(pageNo, pageSize);
        Page<QuestionWithBLOBs> page=null;

        if(user==null){
            return null;
        }
        page=this.questionService.findPage(pageRequest);
        Map<String, Object> data=new HashMap<String, Object>();
        data.put("total", page.getTotalElements());
        data.put("rows", page.getContent());
        return data;
    }
}
